/**
 * @file useRegistOption
 * @author  fanxl
 */
import {computed, unref, type ComputedRef, reactive} from 'vue';
import type {ValuesState, RegisterOptions} from './types';
import type {LikeFieldType} from '../interface';
import {handleStatus} from '../util/spec';

export function useRegistOption(
    fieldProps: ComputedRef<LikeFieldType> | LikeFieldType,
    values: ComputedRef<ValuesState> | ValuesState
) {
    const fieldName = computed(() => unref(fieldProps).path);
    const validators = computed(() => unref(fieldProps).validators || []);
    const {disabled = false, display = 'block', readOnly = false, spec, remove, hidden} = unref(fieldProps);
    const validateFn = (value: any, parent?: any): Promise<Array<string | true>> => {
        if (!unref(validators)) {
            return Promise.resolve([]);
        }
        const asyncFns = unref(validators).map(fn => Promise.resolve(fn(unref(value), unref(parent))));
        return Promise.all(asyncFns);
    };
    const isRemove = computed(() => handleStatus(remove, unref(values), unref(fieldName)));
    const isHidden = computed(() => handleStatus(hidden, unref(values), unref(fieldName)));

    const option = reactive({
        validate: validateFn,
        disabled,
        readOnly,
        display,
        spec,
        isRemove,
        isHidden,
        inlineError: {},
        warning: {},
        tip: {},
        loadingState: {}
    });

    return option as RegisterOptions;
}
